package com.zbb.order.service.Impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbb.base.execption.ZbbBackException;
import com.zbb.base.model.PageParams;
import com.zbb.base.model.PageResult;
import com.zbb.base.model.Result;
import com.zbb.order.feignclient.CommServiceClient;
import com.zbb.order.feignclient.UserServiceClient;
import com.zbb.order.mapper.OrderDetailsMapper;
import com.zbb.order.mapper.OrderInitiateMapper;
import com.zbb.order.mapper.OrderSnapshotMapper;
import com.zbb.order.mapper.PictureMapper;
import com.zbb.order.model.dto.OrderCount;
import com.zbb.order.model.dto.OrderSnapshotDto;
import com.zbb.order.model.po.OrderInitiate;
import com.zbb.order.model.po.OrderSnapshot;
import com.zbb.order.model.po.Picture;
import com.zbb.order.model.po.User;
import com.zbb.order.service.OrderSnapshotService;
import com.zbb.order.util.SecurityUtil;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderSnapshotServiceImpl implements OrderSnapshotService {

    @Autowired
    OrderSnapshotMapper orderSnapshotMapper;

    @Autowired
    PictureMapper pictureMapper;

    @Autowired
    UserServiceClient userServiceClient;

    @Autowired
    CommServiceClient commServiceClient;

    @Autowired
    OrderInitiateMapper orderInitiateMapper;
    @Autowired
    OrderDetailsMapper orderDetailsMapper;


    @Override
    public PageResult<OrderSnapshotDto> getSnapshotList(PageParams pageParams) {
//        获取登录用户信息
        User user = SecurityUtil.getUser();
        QueryWrapper<OrderSnapshot> orderSnapshotQueryWrapper = new QueryWrapper<>();
        orderSnapshotQueryWrapper.eq("group_user_code", user.getId());
        Page<OrderSnapshot> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<OrderSnapshot> pageResult = orderSnapshotMapper.selectPage(page, orderSnapshotQueryWrapper);
        List<OrderSnapshotDto> orderSnapshotDtos = new ArrayList<>();
        // 获取数据列表
        for (OrderSnapshot list : pageResult.getRecords()) {
            OrderSnapshotDto orderSnapshotDto = new OrderSnapshotDto();
            orderSnapshotDto.setSnapshotId(list.getId());
            orderSnapshotDto.setOrderInitiateCode(list.getOrderInitiateCode());
            orderSnapshotDto.setTitle(list.getTitle());
            orderSnapshotDto.setDate(list.getCreateTime());
            orderSnapshotDto.setStatus(list.getStatus());
            orderSnapshotDto.setEvaluationStatus(list.getEvaluationStatus());
            orderSnapshotDto.setGroupUserId(list.getGroupUserCode());
            //翻译状态0未接单，1进行中，2订单已取消，3订单已经完成
            if (list.getStatus() != 0 && list.getStatus() != 8) {
                //获取帮助用户信息
                User user1 = userServiceClient.querytUser(list.getHelpUserCode());
                orderSnapshotDto.setPhone(user1.getPhoneNo());
                orderSnapshotDto.setName(user1.getUserName());
                orderSnapshotDto.setHelpUserId(list.getHelpUserCode());
            } else {
                orderSnapshotDto.setPhone("未知");
                orderSnapshotDto.setName("未知");
            }
            orderSnapshotDtos.add(orderSnapshotDto);
        }
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<OrderSnapshotDto> courseBasePageResult = new PageResult<>(orderSnapshotDtos, total,
                pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;

    }

    @Override
    public PageResult<OrderSnapshotDto> getHelpSnapshotList(PageParams pageParams) {
//        获取登录用户信息
        User user = SecurityUtil.getUser();
        QueryWrapper<OrderSnapshot> orderSnapshotQueryWrapper = new QueryWrapper<>();
        orderSnapshotQueryWrapper.eq("help_user_code", user.getId());
        Page<OrderSnapshot> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<OrderSnapshot> pageResult = orderSnapshotMapper.selectPage(page, orderSnapshotQueryWrapper);
        List<OrderSnapshotDto> orderSnapshotDtos = new ArrayList<>();
        // 获取数据列表
        for (OrderSnapshot list : pageResult.getRecords()) {
            OrderSnapshotDto orderSnapshotDto = new OrderSnapshotDto();
            orderSnapshotDto.setSnapshotId(list.getId());
            orderSnapshotDto.setOrderInitiateCode(list.getOrderInitiateCode());
            orderSnapshotDto.setTitle(list.getTitle());
            orderSnapshotDto.setDate(list.getCreateTime());
            orderSnapshotDto.setStatus(list.getStatus());
            orderSnapshotDto.setEvaluationStatus(list.getEvaluationStatus());
            orderSnapshotDto.setGroupUserId(list.getGroupUserCode());
            if (list.getStatus() != 0 && list.getStatus() != 8) {
                //获取帮助用户信息
                User user1 = userServiceClient.querytUser(list.getGroupUserCode());
                orderSnapshotDto.setPhone(user1.getPhoneNo());
                orderSnapshotDto.setName(user1.getUserName());
                orderSnapshotDto.setHelpUserId(list.getHelpUserCode());
            } else {
                orderSnapshotDto.setPhone("未知");
                orderSnapshotDto.setName("未知");
            }
            orderSnapshotDtos.add(orderSnapshotDto);
        }
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<OrderSnapshotDto> courseBasePageResult = new PageResult<>(orderSnapshotDtos, total,
                pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Transactional
    @Override
    public Result placeOrder(String userId, String initiateId, String detailId) {

        //获取当前用户信息
        User user = SecurityUtil.getUser();
        //修改发起订单状态
        OrderInitiate orderInitiate = orderInitiateMapper.selectById(initiateId);
        if (orderInitiate.getStatus() == 1) {
            throw new ZbbBackException("订单已经被他人接收");
        } else {
            orderInitiate.setStatus(1);
            orderInitiateMapper.updateById(orderInitiate);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_initiate_code", initiateId);
            OrderSnapshot orderSnapshot = orderSnapshotMapper.selectOne(queryWrapper);
            orderSnapshot.setHelpUserCode(user.getId());
            orderSnapshot.setOrderInitiateCode(initiateId);
            orderSnapshot.setStatus(1);
            orderSnapshot.setUpdateTime(LocalDateTime.now());

            //存储订单快照
            orderSnapshotMapper.updateById(orderSnapshot);

//        通知求助用户同意订单。
            commServiceClient.commUserMessage(orderSnapshot);
            return Result.ok();
        }
    }

    @Override
    public Result updateSnapshotOrder(String snapshotId, int status) {
        OrderSnapshot orderSnapshot = orderSnapshotMapper.selectById(snapshotId);
        orderSnapshot.setStatus(status);
        int i = orderSnapshotMapper.updateById(orderSnapshot);
        //        通知求助用户同意订单。
        if (status != 4) {
            commServiceClient.commHelpUserMessage(orderSnapshot);
        } else {
            commServiceClient.commUserMessage(orderSnapshot);
        }
        return Result.ok();
    }

    @Transactional
    @Override
    public Result updateUserStatus() {
        User user = SecurityUtil.getUser();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_user_code", user.getId());
        queryWrapper.eq("status", 4);
        List<OrderSnapshot> orderSnapshots = orderSnapshotMapper.selectList(queryWrapper);
        for (OrderSnapshot orderSnapshot : orderSnapshots) {
            orderSnapshot.setStatus(6);
            orderSnapshotMapper.updateById(orderSnapshot);
        }
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("help_user_code", user.getId());
        queryWrapper1.eq("status", 3);
        List<OrderSnapshot> orderSnapshots1 = orderSnapshotMapper.selectList(queryWrapper1);
        for (OrderSnapshot orderSnapshot : orderSnapshots1) {
            orderSnapshot.setStatus(7);
            orderSnapshotMapper.updateById(orderSnapshot);
        }
        return Result.ok();
    }

    @Override
    public OrderCount getOrderMunCount() {
        User user = SecurityUtil.getUser();
        OrderCount orderCount = orderSnapshotMapper.getOrderCount(user.getId());
        return orderCount;
    }

    @Override
    public OrderSnapshot getUserSnapshotOne() {
        User user = SecurityUtil.getUser();
        OrderSnapshot orderSnapshot = new OrderSnapshot();
        //获取未确认消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("group_user_code", user.getId());
        queryWrapper.eq("status", 1);
        List<OrderSnapshot> orderSnapshots = orderSnapshotMapper.selectList(queryWrapper);
        if (!orderSnapshots.isEmpty()) {
            for (int i = 0; i < orderSnapshots.toArray().length; i++) {
                if (i == 0) {
                    orderSnapshot = orderSnapshots.get(i);
                } else {
                    if (orderSnapshots.get(i).getStartTime().isBefore( orderSnapshot.getStartTime())) {
                        orderSnapshot = orderSnapshots.get(i);
                    }
                }
            }
            return getPhoto(orderSnapshot);
        }
        //获取帮助订单进行中消息
        if (orderSnapshot.getId()==null) {
            QueryWrapper queryHelpWrapper = new QueryWrapper();
            queryHelpWrapper.eq("help_user_code", user.getId());
            queryHelpWrapper.eq("status", 2);
            List<OrderSnapshot> orderSnapshots1 = orderSnapshotMapper.selectList(queryHelpWrapper);
            if (!orderSnapshots1.isEmpty()) {
                for (int i = 0; i < orderSnapshots1.toArray().length; i++) {
                    if (i == 0) {
                        orderSnapshot = orderSnapshots1.get(i);
                    } else {
                        if (orderSnapshots1.get(i).getStartTime().isBefore( orderSnapshot.getStartTime())) {
                            orderSnapshot = orderSnapshots1.get(i);
                        }
                    }
                }
                return getPhoto(orderSnapshot);
            }
        }

        //获取求助订单进行中消息
        if (orderSnapshot.getId()==null) {
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("group_user_code", user.getId());
            queryWrapper2.eq("status", 2);
            List<OrderSnapshot> orderSnapshots2 = orderSnapshotMapper.selectList(queryWrapper2);
            if (!orderSnapshots2.isEmpty()) {
                for (int i = 0; i < orderSnapshots2.toArray().length; i++) {
                    if (i == 0) {
                        orderSnapshot = orderSnapshots2.get(i);
                    } else {
                        if (orderSnapshots2.get(i).getStartTime().isBefore( orderSnapshot.getStartTime())) {
                            orderSnapshot = orderSnapshots2.get(i);
                        }
                    }
                }
                return getPhoto(orderSnapshot);
            }
        }

            //获取帮助订单已经完成消息
            if (orderSnapshot.getId()==null) {
                QueryWrapper queryWrapper3 = new QueryWrapper();
                queryWrapper3.eq("help_user_code", user.getId());
                queryWrapper3.eq("status", 5);
                List<OrderSnapshot> orderSnapshots3 = orderSnapshotMapper.selectList(queryWrapper3);
                if (!orderSnapshots3.isEmpty()) {
                    for (int i = 0; i < orderSnapshots3.toArray().length; i++) {
                        if (i == 0) {
                            orderSnapshot = orderSnapshots3.get(i);
                        } else {
                            if (orderSnapshots3.get(i).getStartTime().isAfter(orderSnapshot.getStartTime())) {
                                orderSnapshot = orderSnapshots3.get(i);
                            }
                        }
                    }
                    return getPhoto(orderSnapshot);
                }
            }
        if (orderSnapshot.getId()==null) {
            QueryWrapper queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("group_user_code", user.getId());
            queryWrapper3.eq("status", 5);
            List<OrderSnapshot> orderSnapshots3 = orderSnapshotMapper.selectList(queryWrapper3);
            if (!orderSnapshots3.isEmpty()) {
                for (int i = 0; i < orderSnapshots3.toArray().length; i++) {
                    if (i == 0) {
                        orderSnapshot = orderSnapshots3.get(i);
                    } else {
                        if (orderSnapshots3.get(i).getStartTime().isAfter(orderSnapshot.getStartTime())) {
                            orderSnapshot = orderSnapshots3.get(i);
                        }
                    }
                }
                return getPhoto(orderSnapshot);
            }
        }
        //获取发出订单
        if (orderSnapshot.getId()==null) {
            QueryWrapper queryWrapper4 = new QueryWrapper();
            queryWrapper4.eq("group_user_code", user.getId());
            queryWrapper4.eq("status", 0);
            List<OrderSnapshot> orderSnapshots4 = orderSnapshotMapper.selectList(queryWrapper4);
            if (!orderSnapshots4.isEmpty()) {
                for (int i = 0; i < orderSnapshots4.toArray().length; i++) {
                    if (i == 0) {
                        orderSnapshot = orderSnapshots4.get(i);
                    } else {
                        if (orderSnapshots4.get(i).getStartTime().isAfter(orderSnapshot.getStartTime())) {
                            orderSnapshot = orderSnapshots4.get(i);
                        }
                    }
                }
                return getPhoto(orderSnapshot);
            }
        }
            return null;
    }

    private OrderSnapshot getPhoto(OrderSnapshot orderSnapshot){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_snapshot_id",orderSnapshot.getId());
        List<Picture> pictures = pictureMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(pictures)) {
            orderSnapshot.setPhotoUrl(pictures.get(0).getUrl());
        }
        return orderSnapshot;
    }
}
